package com.work.util;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName JsoupUtil
 * @Description: Jsoup工具类
 * @Author: WangWenpeng
 * @date: 15:19 2020/1/31
 * @Version 1.0
 */
public class JsoupUtil {
    private static final org.apache.log4j.Logger logger = Logger.getLogger(JsoupUtil.class);

    public static Document page;

    /**
     * @Description 通过Jsoup获取整个页面的信息
     * @Author WangWenpeng
     * @Date 15:22 2020/1/31
     * @Param [url]
     */
    public static void getPageByJSoup(String url) {
        try {
            page = Jsoup.connect(url).get();
            logger.info(page.toString());
            logger.info("看到数据了，开始解析吧");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description 获取具体信息的工具方法
     * key都是id 通过匹配到json格式的数据就能拿到后面的具体信息
     * <script id="getTimelineService">try { window.getTimelineService = [{"id":1119,"pubDate":1580460340000,"pubDateStr":"29分钟前","title":"广东新增确诊病例43例，累计4
     * @Author WangWenpeng
     * @Date 16:36 2020/1/31
     * @Param [regex, attributeKey, attributeValue]
     */
    public static String getInformation(String regex, String attributeKey, String attributeValue) {
        String result = "";
        Pattern p = Pattern.compile(regex);
        Elements timelineService = page.getElementsByAttributeValue(attributeKey, attributeValue);
        Matcher m = p.matcher(timelineService.toString());
        if (m.find()) {
            result = m.group();
        }
        return result;
    }

    /**
     * @Description page.select 根据id拿到值，提高效率
     * @Author WangWenpeng
     * @Date 17:03 2020/2/3
     * @Param [attributeValue, regex]
     */
    public static String getJsonScriptContent(String attributeValue, String regex) {
        Element scriptContent = page.select("script#" + attributeValue).first();
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(scriptContent.toString());
        String jsonContet = "";
        if (m.find()) {
            jsonContet = m.group();
        }
        return jsonContet;
    }
}
